"use strict";

/**
 *
 * phantomjs的一些测试
 * 测试方法切换到当前目录
 * set path=D:\test\spider\phantomjs-2.1.1-windows\bin
 * phantomjs code.js "https://www.baidu.com"
 */

var fs = require('fs');
var system = require('system');
//var env=system.env;
var address = system.args[1];
var url = address;
var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0';

function openPage() {

    //for (var key in env) {
    //    if (env.hasOwnProperty(key)) {
    //        console.log(key + '=' + env[key]);
    //    }
    //}

    page.open(url, function (status) {
        //Page is loaded!

        if (status !== 'success') {
            console.log('Unable to post!');
        } else {
            console.log("start");
            var fileName = "webFile/网站";
            var fileNameHtml = fileName + ".html";
            var fileNamePic = fileName + ".png";
            try {
                //注意这个必须这样不能writeFile
                fs.write(fileNameHtml, page.content, function (err) {
                    if (err) {
                        console.log('写文件操作失败');
                    }
                    else {
                        console.log('写文件操作成功');
                    }
                });
            } catch (e) {
                console.log("save file exp:", e);
            }

            //保存网页为图片
            page.render(fileNamePic);
            console.log("end");
            phantom.exit();
        }
    });
}
openPage();